package com.xupypr.surgery.client;

import java.util.Date;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.xupypr.surgery.client.objects.BlogEntry;

/**
 * Виджет содержащий список элементов блога 
 *  
 * @author Xupypr MV
 */
public class EntriesListWidget extends Composite {
	
	private final AdminPanel adminPanel;

	private LayoutPanel panel = new LayoutPanel();
	private VerticalPanel entries;

	public EntriesListWidget(AdminPanel ap) {
		adminPanel = ap;
		entries = new VerticalPanel();		
		VerticalPanel frame = new VerticalPanel();
		SimplePanel menu = new SimplePanel();
		Image newBtn = new Image();
		newBtn.setUrl("/admin-img/new.png");
		newBtn.setTitle("Новая статья");
		newBtn.addClickHandler(newEntryHandler());
		menu.add(newBtn);
		menu.setHeight("50px");
		frame.add(menu);
		frame.add(entries);
		panel.add(frame);				
		
		initWidget(panel);
		
		getEntries(new Date(), 10);
	}
	
	private ClickHandler newEntryHandler() {
		ClickHandler result = new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				adminPanel.loadEntryToEditor(null);
				adminPanel.switchMode();
			}
		};
		return result;
	}

	private void getEntries(Date borderDate, long quantity) {
		entries.clear();
		adminPanel.getDispatcher().getEntries(borderDate, quantity,
				new AsyncCallback<List<BlogEntry>>() {
					public void onFailure(Throwable caught) {
					}

					public void onSuccess(List<BlogEntry> result) {
						for (BlogEntry entry : result) {
							appendBlogEntry(entry);
						}
					}

				});
	}

	private ClickHandler deleteEntryHandler(Long id) {
		final Long entryId = id;
		ClickHandler delBtnHandler = new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				adminPanel.getDispatcher().deleteEntry(entryId, new AsyncCallback<Void>() {
					@Override
					public void onSuccess(Void result) {
						refresh();
					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO зажурналировать
					}
				});
			}
		};

		return delBtnHandler;
	}

	private void appendBlogEntry(BlogEntry entry) {
		entries.add(showBlogEntry(entry));
	}

	private void addfirstBlogEntry(BlogEntry entry) {
		if (entries.getWidgetCount() > 0) {
			entries.insert(showBlogEntry(entry), 0);
		} else {
			appendBlogEntry(entry);
		}
	}

	private Widget showBlogEntry(BlogEntry entry) {
		FlowPanel blogEntryTemplate = new FlowPanel();

		blogEntryTemplate.add(new HTML(entry.getCreated() + " | "
				+ entry.getCaption()));
		blogEntryTemplate.add(new HTML(entry.getText()));

		FlowPanel buttons = new FlowPanel();

		Image editBtn = new Image();
		editBtn.setUrl("/admin-img/edit.png");
		editBtn.setTitle("Редактировать");
		editBtn.addClickHandler(editEntryHandler(entry.getId()));
		buttons.add(editBtn);

		Image publBtn = new Image();
		publBtn.setUrl((entry.getPublicated()) ? "/admin-img/publicated.png"
				: "/admin-img/depublicated.png");
		publBtn.setTitle((entry.getPublicated()) ? "Опубликовано / скрыть"
				: "Скрыто / опубликовать");
		// TODO: добавить публикацию/депубликацию по клику
		buttons.add(publBtn);

		Image histBtn = new Image();
		histBtn.setUrl("/admin-img/history.png");
		histBtn.setTitle("Просмотреть историю изменений");
		// TODO: добавить возможности просмотра истории
		buttons.add(histBtn);

		Image delBtn = new Image();
		delBtn.setUrl("/admin-img/delete.png");
		delBtn.setTitle("Удалить");
		delBtn.addClickHandler(deleteEntryHandler(entry.getId()));
		buttons.add(delBtn);

		blogEntryTemplate.add(buttons);

		return blogEntryTemplate;
	}

	private ClickHandler editEntryHandler(final Long id) {
		ClickHandler result = new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				adminPanel.loadEntryToEditor(id);
				adminPanel.switchMode();
			}
		};
		return result;
	}

	public void refresh() {
		// TODO Переписать на таймер
		entries.clear();
		getEntries(new Date(), 10);
	}
}
